﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Xml.Linq;

namespace ActiveReportsDemo
{
    public partial class ActiveReportsSite : System.Web.UI.MasterPage
    {
        public string str_siteMenu = "";
        public string categoryID = "";
        public string actionID = "";
        public string reportID = "";
        public string reportType = "";
        public string Title = "ActiveReports  报表应用系统 - 葡萄城控件官方网站";
        public string Description = "";
        public string KeyWords = "";
        public string Introduce = "";
        public string More = "";
        public string ReportURL = "";
        public string ViewType = "";
        public string Height = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            //取URL传参
            categoryID = !String.IsNullOrEmpty(Request.QueryString["category"]) ? Request.QueryString["category"].ToString() : "";
            actionID = !String.IsNullOrEmpty(Request.QueryString["action"]) ? Request.QueryString["action"].ToString() : "";

            //判断是否为报表库
            reportType = !String.IsNullOrEmpty(Request.QueryString["t"]) ? Request.QueryString["t"].ToString() : "";

            string reportID = "";
            XElement xmlDoc;

            if (String.IsNullOrEmpty(reportType))
            {
                xmlDoc = loadXml("Feature");
                //获得xml文件中的ReportID
                reportID = getReportIDFromSiteMenu(actionID, categoryID, xmlDoc);
                str_siteMenu = GetXmlMenu(categoryID, xmlDoc);
            }
            else if (reportType == "lib")
            {
                xmlDoc = loadXml("Library");
                reportID = getReportIDFromSiteMenu(actionID, categoryID, xmlDoc);
                str_siteMenu = GetXmlMenu(categoryID, xmlDoc);
            }
            else if (reportType == "abt")
            {
                xmlDoc = loadXml("About");
                reportID = getReportIDFromSiteMenu(actionID, categoryID, xmlDoc);
                str_siteMenu = GetXmlMenu(categoryID, xmlDoc);
            }

            if (string.IsNullOrEmpty(reportID))
            {
                Title = "ActiveReports 报表应用系统";
                return;
            }
            else
            {
                setData(reportID);
            }

        }

        private string GetXmlMenu(string currentcategory, XElement root)
        {
            StringBuilder sb = new StringBuilder();
            List<XElement> elements = root.Elements().ToList();

            #region <ul>

            // 添加当前 root 节点对应的 HTML 代码
            if (root.Name == "Menu")
            {
                // 当前节点是根节点
                sb.Append("<ul class='page-sidebar-menu'>");
            }
            else if (root.Name == "First")
            {
                // 当前节点是一级菜单
                sb.Append("<ul class='sub-menu'>");
            }
            else if (root.Name == "Second")
            {
                // 当前节点是二级菜单
                sb.Append("<ul class='sub-menu'");

                // 判断菜单中当前选中节点是否在该二级菜单下
                if (categoryID == currentcategory)
                {
                    var selected = root.Elements().Where(i => actionID == i.Attribute("Action").Value).FirstOrDefault();
                    if (selected != null)
                    {
                        // 菜单中当前选中节点在该耳机菜单下，所以为该二级菜单设置 CSS
                        sb.Append(" style='display:block;'");
                    }
                }

                sb.Append(">");
            }

            #endregion

            #region <li>

            // 将当前 root 子节点添加到菜单中
            foreach (XElement element in elements)
            {
                #region <li>

                sb.Append("<li");
                if (element.Attribute("Categoryid") != null)
                {
                    if ((categoryID == element.Attribute("Categoryid").Value) && element.Name == "First")
                    {
                        sb.Append(" class='start active open'");
                    }
                }

                if (element.Attribute("Action") != null)
                {
                    if (categoryID == currentcategory && element.Attribute("Action").Value == actionID)
                    {
                        if (element.Name == "First")
                        {
                            sb.Append(" class='start active open'");
                        }
                        else if (element.Name == "Second")
                        {
                            sb.Append(" class='open'");
                        }
                        else
                        {
                            sb.Append(" class='active'");
                        }
                    }
                }
                sb.Append(">");
                #endregion

                #region <a>
                sb.Append("<a");
                if (!string.IsNullOrEmpty(element.Attribute("Url").Value))
                {
                    sb.Append(" href='");
                    sb.Append(ResolveUrl(element.Attribute("Url").Value));
                    sb.Append("'>");
                }
                if (null != element.Attribute("Icon"))
                {
                    if (string.IsNullOrEmpty(element.Attribute("Url").Value))
                    {
                        sb.Append(">");
                    }

                    sb.Append("<i class='icon-");
                    sb.Append(element.Attribute("Icon").Value);
                    sb.Append("'></i>");
                }
                if (null != element.Attribute("Title"))
                {
                    if (string.IsNullOrEmpty(element.Attribute("Url").Value) && element.Attribute("Icon") == null)
                    {
                        sb.Append(">");
                    }
                    sb.Append(element.Attribute("Title").Value);
                }
                #endregion

                #region </a>
                if (element.HasElements)
                {
                    sb.Append("<span class='arrow'></span>");
                }
                if (element.Attribute("Categoryid") != null)
                {
                    if ((categoryID == element.Attribute("Categoryid").Value) && element.Name == "First")
                    {
                        sb.Append("<span class='selected'></span>");
                    }
                }
                if (element.Attribute("Action") != null)
                {
                    if (categoryID == currentcategory && element.Attribute("Action").Value == categoryID)
                    {
                        sb.Append("<span class='selected'></span>");
                    }
                }
                sb.Append("</a>");
                #endregion

                #region <ul>

                if (element.HasElements)
                {
                    sb.Append(GetXmlMenu(element.Name == "First" ? element.Attribute("Categoryid").Value : currentcategory, element));
                }

                #endregion

                #region </li>

                //if (!element.HasElements)
                //{
                //    sb.Append("</li>");
                //}

                sb.Append("</li>");

                #endregion
            }

            #endregion

            #region </ul>

            sb.Append("</ul>");

            #endregion

            return sb.ToString();
        }

        private string getReportIDFromSiteMenu(string actionid, string categoryid, XElement doc)
        {
            //XElement _doc = loadXml(xmlName);
            string ReportID = "";
            if (String.IsNullOrEmpty(categoryid))
            {
                return "";
            }

            var rootmenu = doc.Elements("First").Where(c => c.Attribute("Categoryid").Value == categoryid).First();
            var node = rootmenu.Elements("Second").Where(c => c.Attribute("Action").Value == actionid).FirstOrDefault();

            if (node == null)
            {
                foreach (XElement item in rootmenu.Elements("Second"))
                {
                    node = item.Elements("Third").Where(c => c.Attribute("Action").Value == actionid).FirstOrDefault();
                    if (node != null)
                    {
                        break;
                    }
                }
            }

            ReportID = (node==null?rootmenu:node).Attribute("ReportID").Value;
            return ReportID;
        }

        private XElement loadXml(String xmlName)
        {
            //获得XML文件服务器地址  siteMenu.xml
            string siteMenuPath = Server.MapPath("~/config/" + xmlName + ".xml");

            //防止异常，判断XML是否存在
            if (!File.Exists(siteMenuPath))
            {
                Response.Write("<script>alert('配置文件错误，请稍后重试！')</script>");
                return null;
            }

            XElement xmlDoc = null;

            String cachaName = "c_" + xmlName;
            //判断缓存，若为空则载入XML文件，相反则直接从内存中调用菜单信息
            if (HttpContext.Current.Cache[cachaName] == null)
            {
                xmlDoc = XElement.Load(siteMenuPath);
                //写入缓存
                HttpContext.Current.Cache.Insert(cachaName, xmlDoc, new CacheDependency(siteMenuPath, DateTime.Now));
            }
            else
            {
                xmlDoc = (System.Xml.Linq.XElement)HttpContext.Current.Cache[cachaName];
            }

            return xmlDoc;
        }

        private DataTable loadReportDescription(String dbname)
        {

            string siteMenuPath = Server.MapPath("~/config/" + dbname + ".mdb");

            if (!File.Exists(siteMenuPath))
            {
                Response.Write("<script>alert('配置文件错误，请稍后重试！')</script>");
                return null;
            }

            DataTable _dt = new DataTable();

            String cachaName = "c_" + dbname;

            if (HttpContext.Current.Cache[cachaName] == null)
            {
                string commandstring = "SELECT * FROM ReportDescription";
                string connectionstring = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};", Server.MapPath("~/config/ReportsResources.mdb"));

                using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(connectionstring))
                {
                    System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(commandstring, connection);
                    System.Data.OleDb.OleDbCommandBuilder builder = new System.Data.OleDb.OleDbCommandBuilder(adapter);

                    adapter.Fill(_dt);
                }
            }
            else
            {
                _dt = (DataTable)HttpContext.Current.Cache[cachaName];
            }
            return _dt;
        }

        private void setData(string reportID)
        {
            XElement reXml = loadXml("ReportResources");
            ResourceList _rl = new ResourceList(reportID, reXml);

            DataTable dt = loadReportDescription("ReportsResources");
            dt.DefaultView.RowFilter = string.Format("ReportID='{0}'", reportID);

            Title = string.Format("{0} - ActiveReports 报表应用系统", _rl.Title);
            KeyWords = _rl.Keywords;
            Description = _rl.Description;
            More = _rl.More;
            ReportURL = _rl.ReportURL;
            ViewType = _rl.ViewType;
            Height = _rl.Height;

            if (dt.DefaultView.Count > 0)
            {
                string content = dt.DefaultView[0]["Description"].ToString();
                content = content.Replace(".aspx", ".aspx?utm_source=Demo&utm_medium=activereports&utm_term=controlexplorer&utm_content=blog&utm_campaign=asp.net");
                Introduce = content;
            }
            else
            {
                Introduce = _rl.Description;
            }
        }
    }
}